import gradio as gr
import requests
import json

# 替换成你的DeepSeek API密钥
DEEPSEEK_API_KEY = "sk-fb9e435ca60340db8a7e11b7d3d2f319"
API_URL = "https://api.deepseek.com/v1/chat/completions"


def ask_deepseek(question, history):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}"
    }

    payload = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "user", "content": question}
        ],
        "temperature": 0.7
    }

    try:
        response = requests.post(API_URL, headers=headers, data=json.dumps(payload))
        response.raise_for_status()
        result = response.json()

        if 'choices' in result and len(result['choices']) > 0:
            return result['choices'][0]['message']['content']
        else:
            return "未收到有效响应"

    except requests.exceptions.RequestException as e:
        return f"请求出错：{str(e)}"
    except json.JSONDecodeError:
        return "响应解析失败"


# 创建Gradio界面
with gr.Blocks(title="DeepSeek问答助手") as demo:
    gr.Markdown("# 🚀 DeepSeek问答助手")
    gr.Markdown("输入你的问题，获取AI回答")

    with gr.Row():
        with gr.Column():
            input_question = gr.Textbox(
                label="输入问题",
                placeholder="请输入你的问题...",
                lines=3
            )
            submit_btn = gr.Button("提交问题", variant="primary")

        output_answer = gr.Textbox(
            label="回答",
            interactive=False,
            lines=5
        )

    # 处理提交事件
    submit_btn.click(
        fn=ask_deepseek,
        inputs=[input_question],
        outputs=output_answer
    )

    # 回车快捷提交
    input_question.submit(
        fn=ask_deepseek,
        inputs=[input_question],
        outputs=output_answer
    )

if __name__ == "__main__":
    demo.launch(server_port=7860, share=False)